import 'dart:convert';
import 'dart:io';


import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:jicaimao_flutter/entity/mersonal_information_bean.dart';
import 'package:jicaimao_flutter/utils/api_address.dart';
import 'package:jicaimao_flutter/utils/http_utils.dart';
import 'package:jicaimao_flutter/utils/sp_key.dart';
import 'package:jicaimao_flutter/utils/sp_utils.dart';
import 'package:jicaimao_flutter/views/mine/my_nickname.dart';
//import 'package:event_bus/event_bus.dart';

class MersonalInformationPage extends StatefulWidget {
  @override
  _MersonalInformationPageState createState() =>
      _MersonalInformationPageState();
}

class _MersonalInformationPageState extends State<MersonalInformationPage> {
  String mHeadImgUrl;
  var mNickName;
  String mPhoneNum;
  String mRegistrationTime;
  String mTreasureBoxAddress;

  ///相机图片
  File _cameraImages;

  @override
  void initState() {
    super.initState();
    String userId = SpUtils.getString(SpKey.KEY_USER_ID);
    // 网络请求数据
    _loadData(userId);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Color(0xFFF6F5F5),
        appBar: AppBar(
          centerTitle: true,
          backgroundColor: Colors.white,
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              color: Colors.grey,
            ),
            onPressed: () => Navigator.pop(context),
          ),
          title: Text(
            '个人信息',
            style: TextStyle(
              fontSize: 16,
              color: Colors.black,
            ),
          ),
        ),
        body: Column(
          children: <Widget>[
            GestureDetector(
              child: Container(
                margin: EdgeInsets.fromLTRB(0.0, 20.0, 0.0, 0.0),
                padding: EdgeInsets.fromLTRB(0.0, 0.0, 20.0, 0.0),
                color: Colors.white,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    ///头像
                    Container(
                      alignment: Alignment.centerRight,
                      margin: EdgeInsets.fromLTRB(0.0, 0.0, 20.0, 0.0),
                      padding: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 10.0),
                      child: ClipOval(
                        child: _cameraImages == null
                            ? FadeInImage.assetNetwork(
                                placeholder: 'images/icon_user_head.png',
                                image: mHeadImgUrl.toString(),
                                height: 45.0,
                                width: 45.0,
                                fit: BoxFit.cover,
                              )
//                            : _Head(context, _cameraImages),
                            : Image.file(
                                _cameraImages,
                                height: 45.0,
                                width: 45.0,
                                fit: BoxFit.cover,
                              ),
                      ),
                    ),
                    new Image.asset(
                      "images/icon_more.png",
                      width: 10.0,
                      height: 10.0,
                    ),
                  ],
                ),
              ),

              ///系统相机
              onTap: () => showSelectBottomDialog(context),
            ),

            ///我的昵称
            GestureDetector(
              child: Container(
                margin: EdgeInsets.fromLTRB(0.0, 1.0, 0.0, 0.0),
                height: 45.0,
                padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 0.0),
                color: Colors.white,
                child: new Row(
                  children: <Widget>[
                    Expanded(
                      child: new Text('用户昵称',
                          style: new TextStyle(
                              fontWeight: FontWeight.normal,
                              fontSize: 15.0,
                              color: Color(0xFF333333))),
                      flex: 3,
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
                      alignment: Alignment.centerRight,
                      child: new Text(mNickName.toString(),
                          style: new TextStyle(
                              fontWeight: FontWeight.normal,
                              fontSize: 15.0,
                              color: Color(0xFF999999))),
                    ),
                    new Image.asset(
                      "images/icon_more.png",
                      width: 10.0,
                      height: 10.0,
                    ),
                  ],
                ),
              ),
              onTap: () {
                _navigatorAndDisplaySelection(context);
//                Navigator.push(
//                  context,
//                  MaterialPageRoute(builder: (context) => MyNickname()),
//                );
//
//                Navigator.of(context).pushNamed('/location');
              },
            ),

            commentTitle(context, mPhoneNum.toString(), '手机号码', 0),
            commentTitle(context, mRegistrationTime.toString(), '注册时间', 0),
            commentTitle(context, mTreasureBoxAddress.toString(), '宝箱地址', 3),
          ],
        ),
      ),
    );
  }

  Widget commentTitle(
      BuildContext context, String content, String title, int type) {
    return new Container(
      margin: EdgeInsets.fromLTRB(0.0, 1.0, 0.0, 0.0),
      padding: EdgeInsets.fromLTRB(15.0, 13.0, 15.0, 13.0),
      color: Colors.white,
      child: new Row(
        children: <Widget>[
          Expanded(
            child: new Text(title,
                maxLines: 1,
                style: new TextStyle(
                    fontWeight: FontWeight.normal,
                    fontSize: 15.0,
                    color: Color(0xFF333333))),
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.fromLTRB(30.0, 0.0, 0.0, 0.0),
              alignment: Alignment.centerRight,
              child: new Text(content,
                  style: new TextStyle(
                      fontWeight: FontWeight.normal,
                      fontSize: 15.0,
                      color: Color(0xFF999999))),
            ),
            flex: type,
          ),
        ],
      ),
    );
  }

  _navigatorAndDisplaySelection(BuildContext context) async {
    var result = await Navigator.push(
        context, new MaterialPageRoute(builder: (context) => new MyNickname()));
    if (result != null) {
      mNickName = result;
    }
  }

  /// 网络获取数据
  Future _loadData(String userId) async {
    String url = NetAddress.mySelfInfo;
    var data = {'userId': userId};
    var respone = await HttpUtil().post(url, data: data);
    setState(() {
      MersonaInformationBean _mBean =
          MersonaInformationBean.fromJson(json.decode(respone));
      mPhoneNum = _mBean.result.mobile;
      mRegistrationTime = _mBean.result.creationTime;
      mTreasureBoxAddress = _mBean.result.walletAddress;
      mNickName = _mBean.result.nickName;
      mHeadImgUrl = _mBean.result.headImgUrl;
    });
  }

  /// 上传头像
  Future UploadHead(File file) async {

    String userId = SpUtils.getString(SpKey.KEY_USER_ID);
    var bytes = utf8.encode(file.toString());
    var encoded1 = base64Encode(bytes);


    var data = {'userId': userId,"headImgUrl":encoded1};
    String url = NetAddress.uploadHead;
    var respone = await HttpUtil().post(url, data: data);

    print("66666file:"+file.toString());
    print("66666bytes:"+bytes.toString());
    print("66666encoded1:"+encoded1.toString());

    setState(() {
//      MersonaInformationBean _mBean =
//          MersonaInformationBean.fromJson(json.decode(respone));
    });
  }

  /// 选择相机  拍照选择框~~~~~~~~~~~
  void showSelectBottomDialog(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Container(
            height: 200.0,
            child: Column(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.all(5.0),
                  color: Colors.white,
                  alignment: Alignment.center,
                  child: Text(
                    '请选择',
                    style: TextStyle(color: Colors.black, fontSize: 18.0),
                  ),
                  height: 40.0,
                ),
                CommonItemSelect(
                  onTabItem: () {
                    Navigator.pop(context);
                    _getImage(ImageSource.camera);
                  },
                  title: '拍照',
                  itemHeight: 50.0,
                ),
                CommonItemSelect(
                  onTabItem: () {
                    Navigator.pop(context);
                    _getImage(ImageSource.gallery);
                  },
                  title: '相册',
                  itemHeight: 50.0,
                ),
                CommonItemSelect(
                  title: '取消',
                  itemHeight: 50.0,
                  color: Colors.grey,
                )
              ],
            ),
          );
        });
  }

  /// 选择 或者 拍照
  void _getImage(ImageSource source) async {
    var image = await ImagePicker.pickImage(source: source);
    if (image == null) {
      return;
    }
    setState(() {
      _cameraImages = image;
      UploadHead(image);
    });
  }
}




class CommonItemSelect extends StatelessWidget {
  CommonItemSelect({this.onTabItem, this.title, this.color, this.itemHeight});

  final String title;
  final Color color;
  final double itemHeight;
  final VoidCallback onTabItem;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTabItem,
      child: Container(
        margin: EdgeInsets.only(top: 1.0),
        color: Colors.white,
        alignment: Alignment.center,
        height: itemHeight,
        child: Text(
          title,
          style: TextStyle(
              color: color == null ? Colors.blue : color, fontSize: 16.0),
        ),
      ),
    );
  }
}
